<?php

namespace App\Http\Middleware;

use App\Services\Auth\JwtService;
use App\Repositories\Auth\WechatUserRepository;
use App\Repositories\Config\EmployeeRepository;
use Closure;
use Illuminate\Http\Request;

class CheckToken
{
    protected $wechatUserRepository;

    protected $EmployeeRepository;

    public function __construct(WechatUserRepository $wechatUserRepository, EmployeeRepository $EmployeeRepository)
    {
        $this->wechatUserRepository = $wechatUserRepository;
        $this->EmployeeRepository = $EmployeeRepository;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request, Closure $next)
    {
        // 获取token
        $token = $request->header('Authorization');

        // 如果没有Authorization头，尝试从请求参数中获取
        if (!$token) {
            $token = $request->input('token');
        }

        // 处理Bearer token格式
        if ($token && strpos($token, 'Bearer ') === 0) {
            $token = substr($token, 7);
        }

        // 验证token是否存在
        if (!$token) {
            return response()->json([
                'code' => 401,
                'message' => '未提供认证令牌',
                'data' => null
            ], 401);
        }

        try {
            // 验证JWT token
            $userId = JwtService::verifyToken($token);

            if (!$userId) {
                return response()->json([
                    'code' => 401,
                    'message' => '无效的认证令牌',
                    'data' => null
                ], 401);
            }

            // 查找用户信息
            $user = $this->wechatUserRepository->find($userId);

            if (!$user) {
                return response()->json([
                    'code' => 401,
                    'message' => '用户不存在',
                    'data' => null
                ], 401);
            }

            // 查询绑定员工
            $employee = $this->EmployeeRepository->findByUseridWithEmployee($userId);

            // if (!$employee) {
            //     return response()->json([
            //         'code' => 401,
            //         'message' => '该微信用户尚未绑定员工信息，请先进行员工绑定',
            //         'data' => null
            //     ], 401);
            // }

            // 将用户信息添加到请求中，供后续使用
            $request->merge(['current_user' => $employee]);
            $request->merge(['user_id' => isset($employee) ? $employee->id : null]);
            $request->merge(['wechat_user' => $user]);
        } catch (\Exception $e) {
            // 记录错误日志
            \Log::error('JWT Token验证失败', [
                'error' => $e->getMessage(),
                'token' => $token,
                'trace' => $e->getTraceAsString()
            ]);

            return response()->json([
                'code' => 401,
                'message' => '认证令牌验证失败',
                'data' => null
            ], 401);
        }

        return $next($request);
    }
}
